﻿using Colorful.CMS.Core;
using Colorful.Models;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Text;
using Colorful.Database;
using Colorful.Captcha;
using Microsoft.AspNetCore.Authorization;

namespace Colorful.API
{
    [AllowAnonymous]
    [Route("cms/guestbook")]
    public class GuestbookController : BaseAPI
    {
        [HttpPost]
        public IActionResult Post(string name, string email, string code)
        {
            try
            {
                using (var db = CMSDbHelper.GetDb())
                {
                    using (var validator = new SubmitService("guestbook", db, 1))
                    {
                        if (validator.IsValidate())
                        {
                            if (string.IsNullOrEmpty(code))
                                return this.GetResult(true, "requireCode");
                            else if (!CaptchaHelper.IsValid(code))
                                return this.GetResult(false, "验证码错误！");
                        }
                        var guestbook = new Guestbook();
                        FormHelper.SafeFill(guestbook, new RequireField("Name", "联系人") { MaxLength = 20, XXSFilter = true }
                            , new TextField("Phone", "联系电话") { XXSFilter = true, MaxLength = 12, }
                            , new EmailField("Email", "邮箱", false) { MaxLength = 30, XXSFilter = true }
                            , new RequireField("Message", "留言内容") { MaxLength = 500, XXSFilter = true });
                        guestbook.Message = System.Web.HttpUtility.HtmlEncode(guestbook.Message);
                        db.Guestbooks.Add(guestbook);
                        return this.GetResult(true);
                    }
                }
            }
            catch (Exception ex)
            {
                return this.GetResult(ex);
            }
        }
    }
}
